<template>
  <div class="app-container">
    <!-- 送货计划维护 -->
    <div class="search-bar">
      <!-- 搜索 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="客户编号" prop="companyCode">
          <el-select-v2
            v-model="queryParams.companyCode"
            filterable
            clearable
            :options="allCompanyCode"
            value-key="value"
            placeholder="请输入客户编号"
            class="!w-[192px]"
            @change="handleQuery()"
          />
        </el-form-item>

        <el-form-item label="送货单号" prop="code">
          <el-input
            v-noSpace
            v-model="queryParams.code"
            placeholder="请输入送货单号"
            clearable
            class="!w-[192px]"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="送货日期" prop="timeScopes">
          <el-date-picker
            v-model="queryParams.timeScopes"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 生产单列表 -->
    </div>

    <!-- 表格 -->
    <el-card shadow="never">
      <el-table v-loading="loading" :data="pageData" @row-click="handClikRow">
        <el-table-column prop="code" label="送货单号" align="center" />
        <el-table-column prop="companyName" label="客户名称" align="center" />
        <el-table-column prop="issueDate" label="送货日期" align="center" />
        <!-- <el-table-column prop="qty" label="配送顺序" align="center" /> -->
        <!-- <el-table-column prop="qty" label="订单数量" align="center" /> -->
        <!-- <el-table-column prop="qty" label="产品信息" align="center" /> -->
        <!-- <el-table-column prop="qty" label="送货单状态" align="center" /> -->
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column label="操作" fixed="right" width="250" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              v-hasPerm="'sys:planDeliverGoods:app'"
              @click="handleApproved(scope.row)"
            >
              确认
            </el-button>
            <el-button
              type="primary"
              v-hasPerm="'sys:planDeliverGoods:edit'"
              size="small"
              link
              @click="handleEdit(scope.row, 'edit')"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              v-hasPerm="'sys:planDeliverGoods:del'"
              size="small"
              link
              @click="handleDel(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormDataRef"
        :model="dialogFormData"
        label-width="120px"
        :disabled="formDisabled"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="送货单号" prop="code">
              <el-input
                v-noSpace
                v-model="dialogFormData.code"
                placeholder="请输入送货单号"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="客户编号" prop="companyCode">
              <el-input
                v-noSpace
                v-model="dialogFormData.companyCode"
                placeholder="请输入客户编号"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="客户名称" prop="companyName">
              <el-input
                v-noSpace
                v-model="dialogFormData.companyName"
                placeholder="请输入客户编号"
                disabled
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="配送顺序" prop="code">
              <el-input v-noSpace v-model="dialogFormData.code" placeholder="请输入配送顺序" />
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="送货日期" prop="issueDate">
              <el-date-picker
                v-model="dialogFormData.issueDate"
                type="date"
                placeholder="选择时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider />
      <p>订单列表</p>

      <!-- <el-form
        ref="dialogFormDataProRef"
        :model="dialogFormDataPro"
        label-width="120px"
        :disabled="formDisabled"
        :rules="rulesPro"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-select
                v-model="dialogFormDataPro.productName"
                placeholder="请选择产品名称"
                clearable
                filterable
                @change="changeproductName"
                @visible-change="getContractList"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="qty">
              <el-input-number v-model="dialogFormDataPro.qty" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12"></el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="addProDuct">添加产品</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form> -->

      <el-table v-loading="loading" :data="rowTableData">
        <el-table-column label="订单编号" align="center" prop="sourceCode" />
        <el-table-column label="客户名称" align="center" prop="companyName" />
        <el-table-column label="送货地址" align="center" prop="shipCode" />
        <el-table-column label="备注" align="center" prop="rowRemark" show-overflow-tooltip />
        <!-- <el-table-column label="数量" align="center">
          <template #default="scope">
            <el-input v-noSpace v-model="scope.row.qty" size="small" :disabled="formDisabled" />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="250" align="center">
          <template #default="scope">
            <el-button type="danger" size="small" link @click="deleteRow(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <template #footer>
        <div v-if="dialog.type != 'view'" class="dialog-footer flex-center">
          <el-button type="primary" v-debounce="submit">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核 -->
    <el-dialog
      v-model="dialogApp.visible"
      :title="dialogApp.title"
      width="500px"
      @close="handleCloseDialogApp"
    >
      <el-input v-noSpace v-model="approvedRemake" type="textarea" placeholder="请输入审核意见" />

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="handlePass('pass')">通 过</el-button>
          <el-button type="primary" @click="handlePass('noPass')">拒绝</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 表格 -->
    <el-card shadow="never" class="mt20">
      <el-table v-loading="loading" :data="rowTableData">
        <el-table-column label="订单编号" align="center" prop="sourceCode" />
        <el-table-column label="客户名称" align="center" prop="companyName" />
        <el-table-column label="送货地址" align="center" prop="shipCode" />
        <el-table-column label="备注" align="center" prop="rowRemark" show-overflow-tooltip />
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import planDeliverGoodsApi, {
  planDeliverGoodsPageVO,
  planDeliverGoodsPageQuery,
} from "@/api/planManage/planDeliverGoods";
import { FormItemRule } from "element-plus/es";

//产品列表 potato carrot beef
const productList = ref<
  {
    codeName: string;
    codeValue: string;
  }[]
>([]);

const options = ref<{ value: string; label: string }[]>([]); // 显式指定类型

// 新增弹窗
const dialog = reactive({
  title: "",
  visible: false,
  type: "",
});

// 审核弹窗
const dialogApp = reactive({
  title: "",
  visible: false,
});

const rules = reactive<Record<string, FormItemRule[]>>({
  // parentCode: [{ required: true, message: "关联生产单是必填项", trigger: "blur" }],
  // companyName: [{ required: true, message: "供应商是必填项", trigger: "blur" }],
  issueDate: [{ required: true, message: "送货日期是必填项", trigger: "blur" }],
});

const rulesPro = reactive<Record<string, FormItemRule[]>>({
  productName: [{ required: true, message: "产品名称是必填项", trigger: ["blur"] }],
  companyName: [{ required: true, message: "供应商是必填项", trigger: ["blur", "change"] }],
  deliveryDate: [{ required: true, message: "采购日期是必填项", trigger: ["blur", "change"] }],
  qty: [
    { required: true, message: "数量是必填项", trigger: ["blur", "change"] },
    { type: "number", message: "数量必须是一个数字", trigger: ["blur", "change"] },
    { min: 0, type: "number", message: "数量必须大于等于0", trigger: ["blur", "change"] },
  ],
  unitPrice: [
    { required: true, message: "单价是必填项", trigger: ["blur", "change"] },
    { type: "number", message: "单价必须是一个数字", trigger: ["blur", "change"] },
    { min: 0, type: "number", message: "单价必须大于等于0", trigger: ["blur", "change"] },
  ],
});

// 审核意见
const approvedRemake = ref("");

const dialogFormDataRef = ref(ElForm);
const dialogFormDataProRef = ref(ElForm);

interface RowTableDataItem {
  productName?: string;
  unit?: string;
  qty?: number;
  unitPrice?: number;
  amount?: number;
  productCode?: string;
}

interface DialogFormData {
  companyCode?: string;
  parentCode?: string;
  companyName?: string;
  issueDate?: string;
  salesDeliveryDetailList?: RowTableDataItem[];
}

interface DialogFormDataPro {
  productName?: string;
  unit?: string;
  qty?: number;
  unitPrice?: number;
  amount?: number;
  productCode?: string;
}

//row信息
const rowObj = ref<any | null>(null);

const formDisabled = ref(false);

interface DialogFormData {
  code?: number;
  companyCode?: string;
  companyName?: string;
  issueDate?: string;
  deliveryDate?: string;
  parentCode?: string;
  productName?: string;
  productCode?: string;
  qty?: 0;
}
const dialogFormData = reactive<DialogFormData>({});

const dialogFormDataPro = reactive<DialogFormDataPro>({});

const rowTableData = ref<RowTableDataItem[]>([]);

// const calculatedAmount = computed(() => {
//   return (dialogFormDataPro.qty || 0) * (dialogFormDataPro.unitPrice || 0);
// });

const filteredStatusList = ref([
  { value: 0, label: "待审额" },
  { value: 1, label: "已审核" },
  { value: 2, label: "审核拒绝" },
  { value: 3, label: "准备中" },
  { value: 4, label: "待生产" },
  { value: 5, label: "生产中" },
  { value: 6, label: "生产完成" },
]);

const optionsCode = ref([
  { value: 0, label: "待审额" },
  { value: 1, label: "已审核" },
  { value: 2, label: "审核拒绝" },
  { value: 3, label: "准备中" },
  { value: 4, label: "待生产" },
  { value: 5, label: "生产中" },
  { value: 6, label: "生产完成" },
]);

const loading = ref(false);

const queryParams = reactive<planDeliverGoodsPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<planDeliverGoodsPageVO[]>();

const allCompanyCode = ref<{ code: string; count: number }[]>([]);

const total = ref(0);

const queryFormRef = ref(ElForm);

// 查询
function handleQuery() {
  loading.value = true;
  console.log("queryParams", queryParams);
  //queryParams.status转为数字数组发送
  queryParams.statusList = queryParams.status ? [Number(queryParams.status)] : [0];

  planDeliverGoodsApi
    .getPage(queryParams)
    .then((data: any) => {
      pageData.value = [...(data.list as any)];
      console.log("data", data);
      total.value = data.total;
      rowTableData.value = [];
    })
    .catch((err) => {
      console.log(err);
      // ElMessage.error(`${err}`);
      // handleCloseDialog();
      // handleResetQuery();
    })
    .finally(() => {
      loading.value = false;
    });
}

function addProDuct() {
  dialogFormDataProRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    // 判断productName是否重复如果重复就不添加
    const isDuplicate = rowTableData.value.some(
      (item) => item.productName === dialogFormDataPro.productName
    );
    if (isDuplicate) {
      ElMessage.error("产品名称重复，请重新选择");
      return;
    }
    rowTableData.value.push({
      productName: dialogFormDataPro.productName,
      unit: "KG",
      qty: dialogFormDataPro.qty,
      unitPrice: dialogFormDataPro.unitPrice,
      productCode: dialogFormDataPro.productCode,
    });
    clearDialogFormDataPro();
  });
}

function clearDialogFormDataPro() {
  let data = {
    productName: "",
    unit: "",
    qty: 0,
    unitPrice: 0,
    amount: 0,
    productCode: "",
  };
  Object.assign(dialogFormDataPro, { ...data });
}

function clearDialogFormData() {
  let data = {
    companyCode: "",
    parentCode: "",
    companyName: "",
    issueDate: "",
    salesDeliveryDetailList: [],
  };
  Object.assign(dialogFormData, { ...data });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  //todo

  handleQuery();
}

function handleEdit(row: any, type: string) {
  if (type == "add") {
    dialog.title = "新增";
    formDisabled.value = false;
  } else if (type == "edit") {
    dialog.title = "修改";
    formDisabled.value = false;
    Object.assign(dialogFormData, row);
    getEditDetail(row);
  } else {
    dialog.title = "查看";
    formDisabled.value = true;
  }
  dialog.type = type;
  dialog.visible = true;
}

function handleDel(row: any) {
  ElMessageBox.confirm("确定要删除该送货单吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      planDeliverGoodsApi
        .delFun({ id: row?.id })
        .then((data: any) => {
          ElMessage.success(`操作成功`);
          handleQuery();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
          // handleCloseDialog();
          // handleResetQuery();
        })
        .finally(() => {});
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}

function handleCloseDialog() {
  dialog.visible = false;
}

//审核
function handleApproved(row: any) {
  planDeliverGoodsApi
    .makeSure({ id: row?.id, status: 1 })
    .then((data: any) => {
      ElMessage.success(`操作成功`);
      handleQuery();
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
      // handleCloseDialog();
      // handleResetQuery();
    })
    .finally(() => {});
}

function handleCloseDialogApp() {
  dialogApp.visible = false;
}

//是否通过
function handlePass(type: string) {
  // const status = type === "pass" ? 3 : 2;
  // SalesAPI.editTSalesOrder({
  //   id: rowObj.value?.id,
  //   status: status,
  //   approvalComment: approvedRemake.value,
  // })
  //   .then((data) => {
  //     ElMessage.success(`操作成功`);
  //     handleQuery();
  //     dialogApp.visible = false;
  //     approvedRemake.value = "";
  //   })
  //   .catch((error) => {
  //     //ElMessage.error(`${error}`); //注释报错弹窗
  //   })
  //   .finally(() => {
  //     loading.value = false;
  //   });
}

function deleteRow(index: any) {
  rowTableData.value?.splice(index, 1);
}

function changeproductName(val: any) {
  dialogFormDataPro.productCode = val.value;
  dialogFormDataPro.productName = val.label;
}

const getContractList = () => {
  planDeliverGoodsApi
    .getTypePage({ pageNum: 1, pageSize: 999, productType: "1" })
    .then((data) => {
      options.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
      }));
    })
    .finally(() => {});
};

function handClikRow(row: any) {
  getEditDetail(row);
}

function getEditDetail(row: any) {
  planDeliverGoodsApi
    .detailList(row?.code)
    .then((data: any) => {
      rowTableData.value = data || [];
      // ElMessage.success(`操作成功`);
      // handleQuery();
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
      // handleCloseDialog();
      // handleResetQuery();
    })
    .finally(() => {});
}

function submit() {
  dialogFormDataRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    if (!rowTableData.value.length) {
      ElMessage.error(`请添加采购明细`);
      return;
    }
    dialogFormData.salesDeliveryDetailList = rowTableData.value;
    planDeliverGoodsApi
      .addformData(dialogFormData)
      .then((data: any) => {
        ElMessage.success(`操作成功`);
        handleQuery();
        dialog.visible = false;
        clearDialogFormDataPro();
        clearDialogFormData();
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {});
  });
}

function handleAllCompanyQuery() {
  planDeliverGoodsApi.getOptionsPage({ pageNum: 1, pageSize: 999 }).then((data: any) => {
    allCompanyCode.value = data.records.map((item: any, idx: number) => ({
      value: item.code,
      label: `${item.code} - ${item.companyName}`,
    }));
  });
}

onMounted(() => {
  handleQuery();
  handleAllCompanyQuery();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
